/* eslint-disable react-hooks/exhaustive-deps */
/*
 * @Author: zy
 * @Date: 2021-10-25 17:21:43
 * @Last Modified by:   lt
 * @Last Modified time: 2021-10-27 15:37:14
 */

import React, { useEffect, useState } from 'react';
import { Button, Form, Input, message, Modal, Space } from 'antd';
import { checkDamageNumber, damageBook } from '@/services/book';

type PropsType = {
  modifyAid: number;
  visible: boolean;
  hideModal: () => void;
};

const BookDamageModal = ({ modifyAid, visible, hideModal }: PropsType) => {
  const [form] = Form.useForm(); // 表单对象
  const [isDisable, setIsDisable] = useState<boolean>(false); //设置提交按钮是否可用
  const [loading, setLoading] = useState(false); //设置确认按钮的loading

  //表单格式
  const Layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };

  /**
   * @description: 表单重置(根据visible值是否变化：重置Field)
   */
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      //Do Something
      form.resetFields();
    }
    return function cleanup() {
      mounted = false;
    };
  }, [visible]);

  /**
   * @description: 损坏数量校验（1、传入数据通过接口传给后端；
   *                            2、根据返回的数据判别是否存在和数据是否渲染
   *                            3、信息提示）
   */
  const checkQuantity = async (event: any) => {
    const demageQuantity = event.target.value === '' ? 0 : event.target.value;
    const params = { aid: modifyAid, demageQuantity };
    const msg = await checkDamageNumber(params);
    if (msg?.code === 10000) {
      const { isExcess } = msg.data;
      if (isExcess) {
        setIsDisable(true);
        message.error('损坏的数量异常');
      } else {
        setIsDisable(false);
      }
    } else {
      setIsDisable(false);
      message.error(msg ? msg.message : '校验失败');
    }
  };

  /**
   * @description: 表单提交(传入数据，调用接口保存表单数据并做信息提示)
   */
  const finishHandler = async (value: any) => {
    setLoading(true);
    const { demageQuantity, remarks } = value;
    let params;
    if (remarks) {
      params = { aid: modifyAid, ...value };
    } else {
      params = { aid: modifyAid, demageQuantity };
    }
    const msg = await damageBook(params);
    if (msg?.code === 10000) {
      setTimeout(() => {
        message.success('提交成功');
        hideModal();
        setLoading(false);
      }, 200);
    } else {
      message.error(msg ? msg.message : '提交失败');
    }
  };

  return (
    <div>
      <Modal
        forceRender
        width={649}
        title="确认损坏"
        visible={visible}
        onCancel={hideModal}
        footer={
          <Space>
            <Button onClick={hideModal}>取消</Button>
            <Button
              type="primary"
              disabled={isDisable}
              loading={loading}
              onClick={() => form.submit()}
            >
              确定
            </Button>
          </Space>
        }
      >
        <Form {...Layout} layout="horizontal" form={form} onFinish={finishHandler}>
          <Form.Item
            validateTrigger="onBlur"
            name="demageQuantity"
            key="demageQuantity"
            label="损坏数量："
            rules={[
              { required: true, message: '请输入损坏数量' },
              { pattern: new RegExp(/^\+?[1-9][0-9]*$/, 'g'), message: '数量为非0正整数' },
            ]}
          >
            <Input
              type="number"
              placeholder="请输入"
              key="demageQuantity"
              onBlur={(e) => checkQuantity(e)}
            />
          </Form.Item>
          <Form.Item name="remarks" key="damageRemarks" label="备注:">
            <Input.TextArea allowClear name="remark" showCount={true} maxLength={100} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BookDamageModal;
